package com.gxuwz.stats.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.mapper.UserMapper;
import com.gxuwz.stats.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User>  implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getByNameAndPassword(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = this.getOne(queryWrapper);

        if (user != null && new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }
//    @Override
//    public User getByNameAndPassword(String username, String password) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", username).eq("password", password);
//        return this.getOne(queryWrapper);
//    }

    @Override
    public String getUserRoleByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username); // 根据用户 ID 查询

        // 获取用户对象
        User user = this.getOne(queryWrapper);

        // 返回用户的 role 字段值
        if (user != null) {
            return user.getRole();
        } else {
            // 如果用户不存在
            return null;
        }
    }
}


